import React, {useState} from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import {LoginApi} from '../request/api'
import MuiAlert from '@material-ui/lab/Alert';
import { useHistory, Link } from 'react-router-dom'

// import "./less/Login.less"

function Alert(props) {
  return <MuiAlert elevation={6} variant="filled" {...props} />;
}

function Copyright() {
  return (
    <Typography variant="body2" color="textSecondary" align="center">
      {'Copyright © '}
      <Link color="inherit" to="http://codesohigh.com">
        零灯枣狼&你单排吧
      </Link>{' '}
      {new Date().getFullYear()}
      {'.'}
    </Typography>
  );
}

const useStyles = makeStyles((theme) => ({
  paper: {
    marginTop: theme.spacing(8),
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    fontSize: '24px'
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main,
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(1),
  },
  submit: {
    margin: theme.spacing(3, 0, 2),
  },
}));

export default function SignIn() {
  // 添加了这段，强行设置html字体大小
  document.querySelector('html').style.fontSize = "24px";
  
  const classes = useStyles();
  // 成功提示
  const [openSuccess, setOpenSuccess] = useState(false);
  // 失败提示
  const [openError, setOpenError] = useState(false);
  // 用户名
  const [username, setUsername] = useState("");
  // 密码
  const [password, setPassword] = useState("");
  // 获取路由
  const history = useHistory()

  // 点击了登录
  function submitFn(){
    LoginApi({
      username,
      password
    }).then(res=>{
      if(res.errCode===0){
        // 成功
        setOpenSuccess(true);
        let token = res.data;
        // 存入token
        localStorage.setItem('x-auth-token', token);
        // 判断是否有actionCode，若没有则设置默认值
        if (!localStorage.getItem('actionCode')) {
          localStorage.setItem('actionCode',"1334411120332562434")
        }
        // 2秒后跳转到首页
        setTimeout(()=>{
          setOpenSuccess(false);
          // 返回首页
          history.push("/home");
        }, 2000)
      }
    }).catch(err=>{
      setOpenError(true);
      setTimeout(()=>{
        setOpenError(false);
      }, 2000)
    })
  }

  return (
    <Container component="main" maxWidth="xs">
      <CssBaseline />
      <div className={classes.paper}>
        <Avatar className={classes.avatar}>
          <LockOutlinedIcon />
        </Avatar>
        <Typography component="h1" variant="h5">
          Login In
        </Typography>
        <form className={classes.form} noValidate>
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="username"
            label="用户名"
            name="username"
            autoComplete="username"
            autoFocus
            value={username}
            onChange={(e)=>setUsername(e.target.value)}
          />
          <TextField
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="password"
            label="密码"
            type="password"
            id="password"
            autoComplete="password"
            value={password}
            onChange={(e)=>setPassword(e.target.value)}
          />
          <span style={{fontSize:20,color:'#bbb'}}>(一致密码：wolfcode123)</span>
          <Button
            type="button"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={submitFn}
          >
            直接登录
          </Button>
          <Grid container>
            <Grid item xs>
              <Link to="/register" variant="body2" style={{color: '#3f51b5'}}>
                前往注册
              </Link>
            </Grid>
          </Grid>
        </form>
      </div>
      <Box mt={8}>
        <Copyright />
      </Box>
      <Alert className="login_alert" style={{display: openSuccess ? 'flex' : 'none'}} severity="success">登录成功，返回上一页</Alert>
      <Alert className="login_alert" style={{display: openError ? 'flex' : 'none'}} severity="error">请重新登录</Alert>
    </Container>
  );
}